/**
 * Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include <stdio.h>
#include <string.h>
#include "pico/stdlib.h"
#include "hardware/spi.h"

#include "f_util.h"
#include "ff.h"
#include "hw_config.h"
#include "my_debug.h"
#include "rtc.h"
#include "sd_card.h"

#include "ff_headers.h"
#include "ff_stdio.h"

#undef assert
#define assert configASSERT
#define fopen ff_fopen
#define fwrite ff_fwrite
#define fread ff_fread
#define fclose ff_fclose
#ifndef FF_DEFINED
#define errno stdioGET_ERRNO()
#define free vPortFree
#define malloc pvPortMalloc
#endif


/*FatFS_SPI_example

   GPIO 16 (pin 21)  MISO/spi0_rx
   GPIO 17 (pin 22)  Chip select
   GPIO 24 (pin 18)  SCK/spi0_sclk
   GPIO 25 (pin 19) MOSI/spi0_tx
   3.3v/5v (pin 36 / pin 39)
   GND     (pin 38)

   Note: SPI devices can have a number of different naming schemes for pins. See
   the Wikipedia page at https://en.wikipedia.org/wiki/Serial_Peripheral_Interface
   for variations.
   The particular device used here uses the same pins for I2C and SPI, hence the
   using of I2C names
*/

typedef struct {
    FATFS fatfs;
    char const *const name;
} fatfs_dscr_t;
static fatfs_dscr_t fatfs_dscrs[2] = {{.name = "0:"}, {.name = "1:"}};
static FATFS *get_fs_by_name(const char *name) {
    for (size_t i = 0; i < count_of(fatfs_dscrs); ++i) {
        if (0 == strcmp(fatfs_dscrs[i].name, name)) {
            return &fatfs_dscrs[i].fatfs;
        }
    }
    return NULL;
}

static void run_mount(char *drive) {
    FATFS *p_fs = get_fs_by_name(drive);
    if (!p_fs) {
        printf("Unknown logical drive number: \"%s\"\n", drive);
        return;
    }
    FRESULT fr = f_mount(p_fs, drive, 1);
    if (FR_OK != fr) printf("f_mount error: %s (%d)\n", FRESULT_str(fr), fr);
}

int main() {
    stdio_init_all();
    sd_init_driver();
    printf("\033[2J\033[H");  // Clear Screen

	run_mount("0:");
	
    FF_FILE *pxFile;
    DWORD buff[ 32 ];

    pxFile = fopen("/roms.txt", "r");
    if (!pxFile)
        printf("fopen(%s): %s (%d)\n", "/roms.txt", strerror(errno), -errno);
    assert(pxFile);

    while (1) {
        fread(buff, 32, 1, pxFile);
        printf("%s", buff);
        sleep_ms(1000);
    }

    free(buff);
    /* Close the file. */
    ff_fclose(pxFile);

    return 0;
}
